//
//  PDF.swift
//  ptbuy
//
//  Created by MyMac on 2024/11/28.
//

import UIKit
import CoreGraphics
import PDFKit
import CoreData
/*
 product:商品信息
 clientSignPath:签名图片路径
 fielName:导出的文件名
 isSign:是否有签名框
 */
func createPDF(product:[ProductPojo],clientSignPath:String,myFileName:String,isSign:Bool) async throws-> String {
    var fileName = ""
    if myFileName.isEmpty{
        fileName = UUID().uuidString.replacingOccurrences(of: "-", with: "")+".pdf"
    }else{
        fileName = myFileName
    }

//    let fileName = "4D300C62D93F48F6AC21142A6318F219.pdf"
    
    // 设置PDF输出文件路径
    let pdfURL = Utils.getDocumentsDirectory().appendingPathComponent(fileName)
    
    // PDF设置
    let pdfDocument = PDFDocument()
    let pdfPage = PDFPage()

    // PDF页面尺寸 (A4)
    let pageWidth: CGFloat = 595.2
    let pageHeight: CGFloat = 841.8
    
    // 创建一个图形上下文（PDF上下文）
    UIGraphicsBeginPDFContextToFile(pdfURL.path, CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight), nil)
    
    // 开始新的PDF页面
    UIGraphicsBeginPDFPage()

    // 获取当前的上下文
    guard let context = UIGraphicsGetCurrentContext() else { return pdfURL.path }
    
    // 设置字体和颜色
    let titleFont = UIFont.boldSystemFont(ofSize: 24)
    let contentFont = UIFont.systemFont(ofSize: 12)
    let titleColor = UIColor.black
    let contentColor = UIColor.black
    
    // 居中标题
    let title = "二手奢侈品交易确认单"
    let titleRect = CGRect(x: (pageWidth - title.size(withAttributes: [.font: titleFont]).width) / 2,
                           y: 40, width: pageWidth, height: 40)
    title.draw(in: titleRect, withAttributes: [.font: titleFont, .foregroundColor: titleColor])
    
    // 绘制表格
    let tableX: CGFloat = 50
    let tableY: CGFloat = 100
    let tableWidth: CGFloat = pageWidth - 100
    let tableHeight: CGFloat = 300
    let rowHeight: CGFloat = 30
    let numberOfRows = product.count
    let numberOfColumns = 7
    
    // 绘制表头
    let headers = ["序号", "名称", "价格", "记录时间", "客户名称", "收购人", "客户电话"]
    for i in 0..<numberOfColumns {
        let headerRect = CGRect(x: tableX + CGFloat(i) * (tableWidth / CGFloat(numberOfColumns)),
                                y: tableY, width: tableWidth / CGFloat(numberOfColumns), height: rowHeight)
        headers[i].draw(in: headerRect, withAttributes: [.font: contentFont, .foregroundColor: contentColor])
        context.stroke(headerRect)  // 绘制表格边框
    }
    
    /*
      这两个用控制数据量大的时候换页做的
     */
    var sum = 0
    var pageY = tableY
    
    // 填充表格数据
    for row in 0..<numberOfRows {
        if(row>0 && row % 22 == 0){
            UIGraphicsBeginPDFPage()
            sum = 0
            pageY = 0
        }
        sum+=1
        for col in 0..<numberOfColumns {
            /*
              新开页数之后y的值不对劲，应该重制一下
             */
            let cellRect = CGRect(x: tableX + CGFloat(col) * (tableWidth / CGFloat(numberOfColumns)),
                                  y: pageY + CGFloat(sum) * rowHeight,
                                  width: tableWidth / CGFloat(numberOfColumns),
                                  height: rowHeight)
            //["序号", "名称", "价格", "记录时间", "客户名称", "收购人", "客户电话"]
            var cellText:String = ""
            if col==0{
                 cellText = "\(row + 1)"
            }
            //名称
            if col==1{
                 cellText = product[row].product_name
            }
            //价格
            if col==2{
                cellText = "\(product[row].product_price)"
            }
            //记录时间
            if col==3{
                cellText = product[row].time
            }
            //客户名称
            if col==4{
                cellText = product[row].clientName
            }
            //收购人
            if col==5{
                cellText = product[row].clientAgentName
            }
            //客户电话
            if col==6{
                cellText = product[row].clientPhone
            }
            cellText.draw(in: cellRect, withAttributes: [.font: contentFont, .foregroundColor: contentColor])
            context.stroke(cellRect)  // 绘制表格边框
            
           
        }
    }
    //是否有签名
    if isSign {
        // 绘制签名栏
        let signatureBoxX: CGFloat = pageWidth - 200
        let signatureBoxY: CGFloat = pageHeight - 100
        let signatureBoxWidth: CGFloat = 150
        let signatureBoxHeight: CGFloat = 50
        let signatureText = "客户签名："
        
        let signatureRect = CGRect(x: signatureBoxX, y: signatureBoxY, width: signatureBoxWidth, height: signatureBoxHeight)
        signatureText.draw(at: CGPoint(x: signatureBoxX - 70, y: signatureBoxY+20), withAttributes: [.font: contentFont, .foregroundColor: contentColor])


            // 绘制签名栏
    //       let signatureWidth: CGFloat = 150
    //       let signatureHeight: CGFloat = 100
    //       let signatureRect = CGRect(x: pageWidth - signatureWidth - 20, y: pageHeight - signatureHeight - 40, width: signatureWidth, height: signatureHeight)
            // 在签名栏插入图片
        if clientSignPath != ""{
            let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                clientSignPath
            )
            if let uiImage = UIImage(
                contentsOfFile: filename.path
            ){
                uiImage.draw(in: signatureRect)
            }
        }

        context.stroke(signatureRect)  // 绘制签名框
    }

    // 结束PDF上下文
    UIGraphicsEndPDFContext()
    
    return fileName
}
